package com.ks.gopush.cli;

import java.util.LinkedList;
import java.util.List;
import com.ks.gopush.cli.exception.GopushServerException;
import com.ks.gopush.cli.utils.HTTPUtils;
import com.ks.gopush.cli.utils.ParserUtils;

import org.json.JSONArray;
import org.json.JSONObject;

public class HTTPInterfaces {
	public Node getNode(String key, Proto proto) throws GopushServerException {
		if (key == null || key.trim().length() == 0 || proto == null) {
			throw new IllegalArgumentException("key 和 proto不能为空");
		}
		String response = null;
		try {
			response = HTTPUtils.get(String.format(GET_NODE, key, proto.getProto()));
			if (response.trim().length() == 0) {
				throw new GopushServerException("服务端响应内容为空");
			}

//			JSONObject jo = JSONObject.fromObject(response);
			JSONObject jo = new JSONObject(response);
			int ret = jo.getInt("ret");
			switch (RetCode.getRetCode(ret)) {
			case SUCCESS:
				JSONObject data = jo.getJSONObject("data");
				if (data == null) {
					throw new GopushServerException("服务端报文有误 [" + response + "]");
				}
				String server = jo.getJSONObject("data").getString("server");
				if (server == null || server.trim().length() == 0) {
					throw new GopushServerException("服务端报文有误 [" + response + "]");
				}
				String[] args = server.split(":");

				return new Node(key, args[0], Integer.parseInt(args[1]));
			case NOT_FOUND_NODE:
				throw new GopushServerException("指定节点已经失效");
			default:
				throw new GopushServerException("错误码: " + ret + ", " + jo.getString("message"));
			}
		} catch (Exception e) {
			throw new GopushServerException("连接异常", e);
		}
	}

	/**
	 * 获取离线消息
	 * 
	 * @param key
	 *            客户端key
//	 * @param mid
//	 *            私有消息ID
//	 * @param pmid
//	 *            公开消息ID
	 * @return
	 */
	public List<PushMessage> getOfflineMessages(String key, Node node) throws GopushServerException {
		if (key == null || key.trim().length() == 0) {
			throw new IllegalArgumentException("key不可为空");
		} else if (node == null) {
			throw new IllegalArgumentException("node不可为空");
		}
		String response = null;
		try {
			response = HTTPUtils.get(String.format(GET_OFFLINE, key, node.getMid(), node.getPmid()));
			if (response.trim().length() == 0) {
//				throw new GopushServerException("服务端响应内容为空");
				throw new GopushServerException("server response null");
			}
//			JSONObject jo = JSONObject.fromObject(response);
			JSONObject jo = new JSONObject(response);
			int ret = jo.getInt("ret");
			switch (RetCode.getRetCode(ret)) {
			case SUCCESS:
				JSONObject data = null;
				if(jo.has("data")){
					data = jo.getJSONObject("data");
				}else{
					return new LinkedList<PushMessage>();
				}
				if (data == null) {
//					throw new GopushServerException("服务端报文有误 [" + response + "]");
					throw new GopushServerException("server response error [" + response + "]");
				} else if (data.length() == 0) {//data.isEmpty()
					return new LinkedList<PushMessage>();
				}
				List<PushMessage> messages = new LinkedList<PushMessage>();
				JSONArray msgs;
				if(data.has("msgs")){
					msgs = data.getJSONArray("msgs");
					if (msgs.length() > 0) {//!msgs.isEmpty()
					/*for (Iterator<?> it = msgs.iterator(); it.hasNext();) {
						PushMessage message = (PushMessage) JSONObject.toBean((JSONObject) it.next(), PushMessage.class);
						node.refreshMid(message.getMid());
						messages.add(message);
					}*/

						for (int i = 0; i < msgs.length(); i++) {
//							PushMessage message = AppUtil.fromJson(msgs.getJSONObject(i).toString(), PushMessage.class);
							PushMessage message = ParserUtils.parsePushMessage(msgs.getJSONObject(i));
							node.refreshMid(message.getMid());
							messages.add(message);
						}
					}
				}
				if(data.has("pmsgs")){
					msgs = data.getJSONArray("pmsgs");
					if (msgs.length() > 0) {//!msgs.isEmpty()
					/*for (Iterator<?> it = msgs.iterator(); it.hasNext();) {
						PushMessage message = (PushMessage) JSONObject.toBean((JSONObject) it.next(), PushMessage.class);
						node.refreshPmid(message.getMid());
						messages.add(message);
					}*/

						for (int i = 0; i < msgs.length(); i++) {
//							PushMessage message = AppUtil.fromJson(msgs.getJSONObject(i).toString(), PushMessage.class);
							PushMessage message = ParserUtils.parsePushMessage(msgs.getJSONObject(i));
							node.refreshPmid(message.getMid());
							messages.add(message);
						}
					}
				}
				return messages;
			case NOT_FOUND_NODE:
//				throw new GopushServerException("指定节点已经失效");
				throw new GopushServerException("point invalid");
			default:
//				throw new GopushServerException("错误码: " + ret + ", " + jo.getString("message"));
				throw new GopushServerException("error code: " + ret + ", " + jo.getString("message"));
			}
		} catch (Exception e) {
//			throw new GopushServerException("连接异常", e);
			throw new GopushServerException("connection exception", e);
		}
	}

	public HTTPInterfaces(String host, int port) {
		this(host, port, false);
	}

	public HTTPInterfaces(String host, int port, boolean isSSL) { // TODO 暂时不支持SSL
		String base = "http://" + host + ":" + port;
		GET_NODE = base + "/kt/server/get?k=%s&p=%d";
		GET_OFFLINE = base + "/1/msg/get?k=%s&m=%d";

	}

	public static void main(String[] args) throws Exception {
		HTTPInterfaces interfaces = new HTTPInterfaces("114.112.93.13", 80);
		Node node = interfaces.getNode("Terry-Mao", Proto.TCP);
		interfaces.getOfflineMessages("Terry-Mao", node);
	}

	private final String GET_NODE;
	private final String GET_OFFLINE;
}
